<template>
  <div class="signature-container">
    <el-card>
      <template #header>
        <el-button type="primary" @click="undoOperation">撤销</el-button>
        <el-button type="primary" @click="reset">重置</el-button>
        <el-button type="primary" @click="save">保存到本地</el-button>
      </template>
      <div>
        <vue-signature-pad
          class="signature-pad"
          width="100%"
          height="300px"
          ref="signaturePadRef"
          :options="options"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref } from "vue";

const signaturePadRef = ref();
const options = {
  penColor: "#000",
  minWidth: 1, //控制画笔最小宽度
  maxWidth: 2.5, //控制画笔最大宽度
};

const undoOperation = () => {
  signaturePadRef.value.undoSignature();
};
const reset = () => {
  signaturePadRef.value.clearSignature();
};

const save = () => {
  const { isEmpty, data } = signaturePadRef.value.saveSignature();
  console.log("isEmpty:", isEmpty);
  console.log("saveSignature data:", data);
  const el = document.createElement("a");
  // 设置 href 为图片经过 base64 编码后的字符串，默认为 png 格式
  el.href = data;

  el.download = `签名_${Date.now()}.png`;
  // 创建一个点击事件并对 a 标签进行触发
  const event = new MouseEvent("click");
  el.dispatchEvent(event);
};
</script>

<style lang="scss" scoped>
.signature-container {
  .signature-pad {
    border: 1px solid #e6e6e6;
  }
}
</style>
